/**
 * ClickHouse-MySQL同步工具前端JavaScript
 * 实现与后端API的交互和前端功能
 */
document.addEventListener('DOMContentLoaded', function () {
    // DOM元素
    const syncStatusElem = document.getElementById('sync-status');
    const syncModeElem = document.getElementById('sync-mode');
    const syncTablesElem = document.getElementById('sync-tables');
    const tableSelectElem = document.getElementById('table-select');
    const tableSchemaBodyElem = document.getElementById('table-schema-body');

    // 按钮元素
    const btnInit = document.getElementById('btn-init');
    const btnStart = document.getElementById('btn-start');
    const btnStop = document.getElementById('btn-stop');
    const btnFullSync = document.getElementById('btn-full-sync');

    // 模态框相关元素
    const messageModal = new bootstrap.Modal(document.getElementById('message-modal'));
    const modalTitle = document.getElementById('modal-title');
    const modalBody = document.getElementById('modal-body');

    // 初始化页面
    init();

    // 绑定事件处理程序
    btnInit.addEventListener('click', initSync);
    btnStart.addEventListener('click', startIncrementalSync);
    btnStop.addEventListener('click', stopIncrementalSync);
    btnFullSync.addEventListener('click', doFullSync);
    tableSelectElem.addEventListener('change', loadTableSchema);

    /**
     * 初始化页面
     */
    function init() {
        // 加载同步状态
        loadSyncStatus();
    }

    /**
     * 加载同步状态
     */
    function loadSyncStatus() {
        fetch('/api/sync/status')
            .then(response => response.json())
            .then(data => {
                if (data.status) {
                    syncStatusElem.textContent = data.status;

                    // 根据状态启用/禁用按钮
                    if (data.status === '增量同步运行中') {
                        btnStart.disabled = true;
                        btnStop.disabled = false;
                    } else {
                        btnStart.disabled = false;
                        btnStop.disabled = true;
                    }

                    // 显示同步模式和表信息
                    if (data.mode) {
                        let modeText = '';
                        switch (data.mode) {
                            case 'full':
                                modeText = '全量同步';
                                break;
                            case 'incremental':
                                modeText = '增量同步';
                                break;
                            case 'full_incremental':
                                modeText = '全量+增量同步';
                                break;
                            default:
                                modeText = data.mode;
                        }
                        syncModeElem.textContent = modeText;
                    }

                    if (data.tables && data.tables.length > 0) {
                        syncTablesElem.textContent = data.tables.join(', ');

                        // 更新表下拉框
                        tableSelectElem.innerHTML = '<option value="">-- 选择表 --</option>';
                        data.tables.forEach(table => {
                            const option = document.createElement('option');
                            option.value = table;
                            option.textContent = table;
                            tableSelectElem.appendChild(option);
                        });

                        // 启用全量同步按钮
                        btnFullSync.disabled = true;
                    }
                }
            })
            .catch(error => {
                console.error('获取同步状态失败:', error);
                showMessage('错误', '获取同步状态失败: ' + error.message);
            });
    }

    /**
     * 初始化同步环境
     */
    function initSync() {
        btnInit.disabled = true;
        btnInit.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 初始化中...';

        fetch('/api/sync/init', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('成功', data.message);
                    setTimeout(() => {
                        loadSyncStatus();
                        btnStart.disabled = false;
                    }, 1000);
                } else {
                    showMessage('错误', data.message);
                }
            })
            .catch(error => {
                console.error('初始化同步环境失败:', error);
                showMessage('错误', '初始化同步环境失败: ' + error.message);
            })
            .finally(() => {
                btnInit.disabled = false;
                btnInit.innerHTML = '初始化同步环境';
            });
    }

    /**
     * 开始增量同步
     */
    function startIncrementalSync() {
        btnStart.disabled = true;
        btnStart.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 启动中...';

        fetch('/api/sync/incremental/start', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('成功', data.message);
                    setTimeout(() => {
                        loadSyncStatus();
                    }, 1000);
                } else {
                    showMessage('错误', data.message);
                }
            })
            .catch(error => {
                console.error('开始增量同步失败:', error);
                showMessage('错误', '开始增量同步失败: ' + error.message);
            })
            .finally(() => {
                btnStart.innerHTML = '开始增量同步';
            });
    }

    /**
     * 停止增量同步
     */
    function stopIncrementalSync() {
        btnStop.disabled = true;
        btnStop.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 停止中...';

        fetch('/api/sync/incremental/stop', {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('成功', data.message);
                    setTimeout(() => {
                        loadSyncStatus();
                    }, 1000);
                } else {
                    showMessage('错误', data.message);
                }
            })
            .catch(error => {
                console.error('停止增量同步失败:', error);
                showMessage('错误', '停止增量同步失败: ' + error.message);
            })
            .finally(() => {
                btnStop.innerHTML = '停止增量同步';
            });
    }

    /**
     * 执行全量同步
     */
    function doFullSync() {
        const tableName = tableSelectElem.value;
        if (!tableName) {
            showMessage('警告', '请选择要同步的表');
            return;
        }

        btnFullSync.disabled = true;
        btnFullSync.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 同步中...';

        fetch(`/api/sync/full/${tableName}`, {
            method: 'POST'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('成功', data.message);
                } else {
                    showMessage('错误', data.message);
                }
            })
            .catch(error => {
                console.error('全量同步失败:', error);
                showMessage('错误', '全量同步失败: ' + error.message);
            })
            .finally(() => {
                btnFullSync.disabled = false;
                btnFullSync.innerHTML = '执行全量同步';
            });
    }

    /**
     * 加载表结构信息
     */
    function loadTableSchema() {
        const tableName = tableSelectElem.value;
        if (!tableName) {
            tableSchemaBodyElem.innerHTML = '<tr><td colspan="6" class="text-center">请选择表</td></tr>';
            btnFullSync.disabled = true;
            return;
        }

        tableSchemaBodyElem.innerHTML = '<tr><td colspan="6" class="text-center"><div class="spinner-border spinner-border-sm" role="status"></div> 加载中...</td></tr>';

        fetch(`/api/sync/table/${tableName}`)
            .then(response => response.json())
            .then(data => {
                if (data && data.columns) {
                    // 启用全量同步按钮
                    btnFullSync.disabled = false;

                    // 显示表结构
                    tableSchemaBodyElem.innerHTML = '';
                    data.columns.forEach(column => {
                        const row = document.createElement('tr');

                        // 字段名
                        const nameCell = document.createElement('td');
                        nameCell.textContent = column.name;
                        row.appendChild(nameCell);

                        // MySQL类型
                        const mysqlTypeCell = document.createElement('td');
                        mysqlTypeCell.textContent = column.mysqlType;
                        row.appendChild(mysqlTypeCell);

                        // ClickHouse类型
                        const clickhouseTypeCell = document.createElement('td');
                        clickhouseTypeCell.textContent = column.clickhouseType;
                        row.appendChild(clickhouseTypeCell);

                        // 可为空
                        const nullableCell = document.createElement('td');
                        nullableCell.textContent = column.nullable ? '是' : '否';
                        row.appendChild(nullableCell);

                        // 主键
                        const primaryKeyCell = document.createElement('td');
                        primaryKeyCell.textContent = column.primaryKey ? '是' : '否';
                        row.appendChild(primaryKeyCell);

                        // 注释
                        const commentCell = document.createElement('td');
                        commentCell.textContent = column.comment || '';
                        row.appendChild(commentCell);

                        tableSchemaBodyElem.appendChild(row);
                    });
                } else {
                    tableSchemaBodyElem.innerHTML = '<tr><td colspan="6" class="text-center">无法获取表结构信息</td></tr>';
                    btnFullSync.disabled = true;
                }
            })
            .catch(error => {
                console.error('获取表结构失败:', error);
                tableSchemaBodyElem.innerHTML = '<tr><td colspan="6" class="text-center text-danger">获取表结构失败</td></tr>';
                btnFullSync.disabled = true;
            });
    }

    /**
     * 显示消息模态框
     * 
     * @param {string} title 标题
     * @param {string} message 消息内容
     */
    function showMessage(title, message) {
        modalTitle.textContent = title;
        modalBody.textContent = message;
        messageModal.show();
    }
}); 